<?php
//声明
namespace App\Http\Controllers\Api\v1;
//引用
use App\Http\Controllers\Controller;
use App\Models\Comment;
use App\Models\Shop;
use App\Repositories\AddressRepository;
use App\Repositories\CommentRepository;
use App\Tools\Map;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

//控制器类
class CommentController extends Controller
{

    protected $commentRepository;
    /**
     * AddressController constructor.
     * @param $AddressRepository
     */
    //绑定生产者
    public function __construct(CommentRepository $commentRepository) {
        $this->commentRepository = $commentRepository;
    }

    // 用户提交评论
    public function comment() {
        $user_id = 1;   // 用户ID 假数据
        $this->validate(request(),[
            'shop_id' =>'required|exists:shops,id',
            'order_id' => 'required|exists:orders,id',
            'content' => 'required|min:10',
        ]);

        $params = array_merge(
            request(['shop_id', 'content','order_id']),
            compact('user_id')
        );
        $count = \App\Models\Comment::where('order_id',request('order_id'))->count();
        if ($count >0){
            return show(200,'comment failed');
        }
        \App\Models\Comment::create($params);
        return show(200,'ok');
    }

    // 获取商家所有评论
    public function shopComments(Request $request){
        $rules = [
            'shop_id'=>'required|integer|exists:shops,id',
        ];
        $message = [
            'shop_id.*' => '商家信息有误'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        $shop_id = request('shop_id',$request->shop_id);
        $res = \App\Models\Comment::with('users')->where('shop_id',$shop_id)->paginate(15);
        return show(200,'ok',$res);
    }

    // 获取用户所有评论
    public function userComments(){
        $user_id = request('user_id',1);
        if (!$user_id){
            return show(200,'failed');
        }
        $count = 2;
        $res = \App\Models\Comment::where('user_id',$user_id)->paginate($count);
        return show(200,'ok',$res);
    }
}
